Events in Asp.Net

An event-driven method of creating ASP.NET web applications is with PHP and Classic ASP, you have a file, which executes the line after the line, from start to finish. However, ASP.net is very different. Here we have incidents, which are activated by the user in one or the other way. In the previous example, we used the Page_load method. Actually, this is an event, which makes page class calls when page is loaded. We will use the same technique in the next example, where we will add some control to our simple hello world example. To make it a bit more interesting, we will change the word "world" with something defined by the user. Take a look at this codelisting, where we add two new controls: one button control and text box control.


<form id="form1" runat="server">
<div>
    <asp:Label runat="server" id="HelloWorldLabel"></asp:Label>
    <br /><br />
    <asp:TextBox runat="server" id="TextInput" /> 
    <asp:Button runat="server" id="GreetButton" text="Say Hello!" />
</div>
</form>

As you can see, now we have added 2 new controls, but they can not really do much at this time. If you want to check this for yourself, you can run the example - if you click on the button, the page is simply reloaded. Let's change it, and start it in an easy way. VS comes with a WYSIWYG editor, and when I rarely use it myself, it makes some things easier, such as to create an event.

Therefore, V. S. Click the Design button below. You will now see a visual representation of our page. We want to add a click event on the button, and this is very simple - just click the greeting button twice, and you will be taken to the codebahind file of our page. As you can see, a good new method has been added, which is called GreetButton_Click. If you look at the Default.aspx file (you should go from Design View to Source View), you will see which method calls to call a button, adds an attribute to our buttons control is. All this work was done with a simple DoubleClick.

Now we can add some code to our new event. We want to use text from the text box, on our good old label "Hello, world!" Lesson This is also very simple, and it's a line of code required:


HelloWorldLabel.Text = "Hello, " + TextInput.Text;

Run the project again (F6), and you will see our old page with some new controls. "Hello, world!" The text is still there, because we set it to page_load event. Now try to enter a name in the text box, and press the button. Now, the text has changed, and we have just used our first control event. Notice how we can add code that is not necessarily called unless the user does a specific job. It's different from the good old classic ASP / PHP perspective, but you'll use it soon, and you'll probably love it!